package com.coda.service.impl;

import com.coda.common.Result;
import com.coda.entity.ProductType;
import com.coda.mapper.ProductTypeMapper;
import com.coda.service.ProductService;
import com.coda.service.ProductTypeService;
import net.bytebuddy.description.type.TypeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@CacheConfig(cacheNames = "productTypeCache")
@Service
public class ProductTypeServiceImpl implements ProductTypeService {

    @Autowired
    private ProductTypeMapper productTypeMapper;

    /**
     * 查询所有分类树
     *
     * @return
     */
    @Cacheable(key = "'productType:tree'")
    @Override
    public List<ProductType> getProductTypeList() {
        List<ProductType> productTypeList = productTypeMapper.getProductTypeList();
        List<ProductType> productTypeTree = getProductTypeTree(productTypeList, 0);
        return productTypeTree;
    }

    /**
     * 根据分类编码查询分类方法
     * @param typeCode
     * @return
     */
    @Override
    public ProductType getProductTypeByCode(String typeCode) {
        ProductType productType = productTypeMapper.getProductTypeByCode(typeCode);
        return productType;
    }

    /**
     * 添加商品分类
     * @param productType
     */
    @CacheEvict(key = "'productType:tree'")
    @Override
    public void addProductType(ProductType productType) {
        productTypeMapper.addProductType(productType);
    }

    /**
     * 根据id删除分类
     * @param id
     */
    @Override
    @CacheEvict(key = "'productType:tree'")
    public void deleteProductTypeById(Long id) {
        productTypeMapper.deleteById(id);
    }

    /**
     * 更新商品分类
     * @param productType
     */
    @CacheEvict(key = "'productType:tree'")
    @Override
    public void update(ProductType productType) {
        productTypeMapper.update(productType);
    }

    /**
     * 递归算法获取商品类型树
     */
    public List<ProductType> getProductTypeTree(List<ProductType> TypeList, Integer pid) {

        // 创建集合用于存储类型树
        List<ProductType> productTypeTree = new ArrayList<>();

        // 遍历所有类型
        for (ProductType productType : TypeList) {
            // 如果该类型的父类型id==当前id，则添加
            if (productType.getParentId().equals(pid)) {
                productTypeTree.add(productType);
            }
        }

        // 遍历存储类型树的集合
        for (ProductType productType : productTypeTree) {
            // 递归，获取二级菜单并添加
            List<ProductType> childProductCategory = getProductTypeTree(TypeList, productType.getTypeId());
            productType.setChildProductCategory(childProductCategory);
        }

        return productTypeTree;
    }
}
